<template>
	<!-- 任务管理  进行中  已完成的任务  -->
	<div class="app-container">
		<!-- 使用搜索组件 -->
		<searchOption id="searchForm" ref="searchUnit" :total="total" @searchList="parentSearchList">
		</searchOption>
		<vxe-table border ref="xTable" size="mini" show-overflow :data="infoList" :column-config="{ resizable: false }"
			:edit-config="{ trigger: 'click', mode: 'cell', enabled: queryParams.status == 5 ? false : true }"
			@scroll="srcollFn" :height="autoTableHeight" :row-style="rowStyle"
			:row-config="{ isCurrent: true, isHover: true }">
			<vxe-colgroup fixed="left">
				<vxe-column field="contractType" title="任务类型" width="70" :visible="queryParams.contractType == -1">
					<template #default="{ row }">
						<dict-tag style="display: inline;" :options="dict.type.contract_type" :value="row.contractType" />
					</template>
				</vxe-column>
				<vxe-column field="countdown"
					:title="(queryParams.contractType == 2 || queryParams.contractType == 1) ? '天数' : '任务周期'" width="60">
					<template #default="{ row }">
						<span style="color: red;">{{ formatDate(row.gmtCreate, row.taskStatus) }}</span>
					</template>
				</vxe-column>
				<vxe-column field="customName" title="公司名称" :edit-render="{ autofocus: '.vxe-input--inner' }" width="160"
					:resizable="true">
					<template #edit="{ row }">
						<vxe-input v-model="row.customName" type="text" placeholder="请输入公司名称" @blur="nameChangeEvent({ row })">
						</vxe-input>
					</template>
				</vxe-column>

				<vxe-column field="bussionEntrustText" title="业务描述" width="70">
					<template #default="{ row }">
						<el-popover placement="bottom" width="720" v-if="row.taskId !== null" trigger="click"
							@show="popoverImg(row, 2)">
							<span slot="reference" style="color: #1890ff;cursor: pointer;">查看描述</span>
							<img v-if="imageSrc !== ''" :src="imageSrc" style="width: 700px" />
						</el-popover>
					</template>
				</vxe-column>

				<vxe-column field="customManager" title="销售经理" :edit-render="{ autofocus: '.vxe-input--inner' }" width="75">
					<template #edit="{ row }">
						<vxe-input v-model="row.customManager" type="text" placeholder="请输入销售经理" @blur="nameChangeEvent({ row })">
						</vxe-input>
						<!-- <vxe-input v-model="row.customManager" type="number" placeholder="请输入数值"></vxe-input> -->
					</template>
				</vxe-column>
			</vxe-colgroup>

			<vxe-column field="customNumber" title="公司证号" :edit-render="{ autofocus: '.vxe-input--inner' }" width="150">
				<template #edit="{ row }">
					<vxe-input v-model="row.customNumber" type="text" placeholder="请输入公司证号" @blur="nameChangeEvent({ row })">
					</vxe-input>
				</template>
			</vxe-column>

			<vxe-column field="region" title="所属区域" :edit-render="{ autofocus: '.vxe-input--inner' }" width="75">
				<template #edit="{ row }">
					<vxe-input v-model="row.region" type="text" placeholder="请输入所属区域" @blur="nameChangeEvent({ row })">
					</vxe-input>
				</template>
			</vxe-column>

			<vxe-column field="taskStatus" title="状态" width="62">
				<template #default="{ row }">
					<span v-if="row.taskStatus == 1" style="color: rgb(230, 162, 60);">进行中</span>
					<span v-if="row.taskStatus == 2" style="color: rgb(245, 108, 108);">暂停</span>
					<span v-if="row.taskStatus == 3" style="color: rgb(245, 108, 108);">作废</span>
					<span v-if="row.taskStatus == 4" style="color: rgb(103, 194, 58);">已完成</span>
				</template>
			</vxe-column>

			<vxe-column field="legalName" title="法人" :edit-render="{ autofocus: '.vxe-input--inner' }" width="62">
				<template #edit="{ row }">
					<vxe-input v-model="row.legalName" type="text" placeholder="请输入法人姓名" @blur="nameChangeEvent({ row })">
					</vxe-input>
				</template>
			</vxe-column>
			<vxe-column field="legalPersonNumber" title="法人身份证" :edit-render="{ autofocus: '.vxe-input--inner' }" width="145">
				<template #edit="{ row }">
					<vxe-input v-model="row.legalPersonNumber" type="text" placeholder="请输入法人身份证"
						@blur="nameChangeEvent({ row })"></vxe-input>
				</template>
			</vxe-column>
			<vxe-column field="legalPersonPhone" title="法人电话" :edit-render="{ autofocus: '.vxe-input--inner' }" width="100">
				<template #edit="{ row }">
					<vxe-input v-model="row.legalPersonPhone" type="text" @blur="nameChangeEvent({ row })"></vxe-input>
				</template>
			</vxe-column>

			<vxe-column field="callPhone" title="联系人电话" :edit-render="{ autofocus: '.vxe-input--inner' }" width="100">
				<template #edit="{ row }">
					<vxe-input v-model="row.callPhone" type="text" @blur="nameChangeEvent({ row })"></vxe-input>
				</template>
			</vxe-column>

			<vxe-column field="taskDesc" title="任务描述" :edit-render="{ autofocus: '.vxe-input--inner' }" width="150">
				<template #edit="{ row }">
					<vxe-input v-model="row.taskDesc" type="text" @blur="nameChangeEvent({ row })"></vxe-input>
				</template>
			</vxe-column>

			<vxe-column field="taxPassword" title="税务密码" :edit-render="{ autofocus: '.vxe-input--inner' }" width="80"
				:visible="taxVisible">
				<template #edit="{ row }">
					<vxe-input v-model="row.taxPassword" type="text" placeholder="请输入税务密码" @blur="nameChangeEvent({ row })">
					</vxe-input>
				</template>
			</vxe-column>

			<vxe-column field="personPassword" title="个税密码" :edit-render="{ autofocus: '.vxe-input--inner' }" width="80"
				:visible="taxVisible">
				<template #edit="{ row }">
					<vxe-input v-model="row.personPassword" type="text" placeholder="请输入个税密码" @blur="nameChangeEvent({ row })">
					</vxe-input>
				</template>
			</vxe-column>

			<vxe-column field="accountBank" title="开户行名称" :edit-render="{ autofocus: '.vxe-input--inner' }" width="120"
				:visible="queryParams.contractType == 1 || queryParams.contractType == 2">
				<template #edit="{ row }">
					<vxe-input v-model="row.accountBank" type="text" placeholder="请输入开户行名称" @blur="nameChangeEvent({ row })">
					</vxe-input>
				</template>
			</vxe-column>

			<vxe-column field="bankManagerPhone" title="开户行经理电话" :edit-render="{ autofocus: '.vxe-input--inner' }" width="110"
				:visible="queryParams.contractType == 1 || queryParams.contractType == 2">
				<template #edit="{ row }">
					<vxe-input v-model="row.bankManagerPhone" type="text" placeholder="请输入开户行客户经理电话"
						@blur="nameChangeEvent({ row })"></vxe-input>
				</template>
			</vxe-column>

			<vxe-column field="madeSignCompanyName" title="刻章公司名称" :edit-render="{ autofocus: '.vxe-input--inner' }"
				width="180"
				:visible="queryParams.contractType != 3 && queryParams.contractType != 4 && queryParams.contractType != 200">
				<template #edit="{ row }">
					<vxe-input v-model="row.madeSignCompanyName" type="text" placeholder="请输入刻章公司名称"
						@blur="nameChangeEvent({ row })"></vxe-input>
				</template>
			</vxe-column>

			<vxe-column field="openName" title="开户人" :edit-render="{ autofocus: '.vxe-input--inner' }" width="70"
				:visible="queryParams.contractType != 3 && queryParams.contractType != 4 && queryParams.contractType != 200">
				<template #edit="{ row }">
					<vxe-input v-model="row.openName" type="text" placeholder="请输入开户人" @blur="nameChangeEvent({ row })">
					</vxe-input>
				</template>
			</vxe-column>

			<vxe-column field="adressDetail" title="地址详情" :edit-render="{ autofocus: '.vxe-input--inner' }" width="200"
				:visible="queryParams.contractType != 3 && queryParams.contractType != 4 && queryParams.contractType != 200">
				<template #edit="{ row }">
					<vxe-input v-model="row.adressDetail" type="text" placeholder="请输入地址详情" @blur="nameChangeEvent({ row })">
					</vxe-input>
				</template>
			</vxe-column>

			<vxe-column field="accountNo" title="账套号" :edit-render="{ autofocus: '.vxe-input--inner' }" width="70"
				:visible="queryParams.contractType == 2 || queryParams.contractType == 5">
				<template #edit="{ row }">
					<vxe-input v-model="row.accountNo" type="text" placeholder="请输入账套号" @blur="nameChangeEvent({ row })">
					</vxe-input>
				</template>
			</vxe-column>

			<!-- 循环渲染图片上传 -->
			<vxe-column v-for="item in uploadImgItem" :key="item.dictValue" :title="item.dictLabel"
				:width="item.dictLabel.length * 10 + 40" align="center">
				<template #default="{ row }">
					<span v-if="imgPath(row, item.dictValue)">客户未涉及</span>
					<!--  @click="uploadTableImg({ row }, item.dictValue)" -->
					<el-button v-else size="mini" type="text">
						<el-popover placement="bottom" width="720" v-if="contractItem(row, item.dictValue)" trigger="manual">
							<span slot="reference" @click="popoverFc({ row }, item.dictValue)">
								<span class="iconfont ali-iconchakan" style="font-size: 15px;color: #13ce66;"></span>
								<span style="color: #13ce66;vertical-align:text-top;margin-left:3px;">查看</span>
							</span>
							<img v-if="imageSrc !== ''" :src="imageSrc" width="700px" />
							<el-button v-show="imageSrc !== ''" size="mini" type="primary" style="float: right;margin-top: 5px;"
								@click="downLoadImg()">下载图片</el-button>
						</el-popover>
						<span v-else-if="queryParams.status != 5" @click="uploadTableImg({ row }, item.dictValue, false)">
							<span>上传图片</span>
							<span style="margin-left: 3px" @click.stop="noNeedToUpload({ row }, item.dictValue)"> 无 </span>
						</span>
					</el-button>
				</template>
			</vxe-column>

			<vxe-column field="accumulationFundTime" title="公积金开启时间" :edit-render="{ autofocus: '.vxe-input--inner' }"
				width="125" :visible="queryParams.contractType == 1 || queryParams.contractType == 2">
				<template #edit="{ row }">
					<vxe-input v-model="row.accumulationFundTime" type="date" placeholder="请选择日期" transfer
						@change="nameChangeEvent({ row })"></vxe-input>
				</template>
			</vxe-column>

			<vxe-column field="socialSecurityTime" title="社保开启时间" :edit-render="{ autofocus: '.vxe-input--inner' }"
				width="125" :visible="queryParams.contractType == 1 || queryParams.contractType == 2">
				<template #edit="{ row }">
					<vxe-input v-model="row.socialSecurityTime" type="date" placeholder="请选择日期" transfer
						@change="nameChangeEvent({ row })"></vxe-input>
				</template>
			</vxe-column>

			<vxe-column field="businessLicenseStart" title="营业执照公示开始时间" :edit-render="{ autofocus: '.vxe-input--inner' }"
				width="150" :visible="queryParams.contractType == 4">
				<template #edit="{ row }">
					<vxe-input v-model="row.businessLicenseStart" type="date" placeholder="请选择日期" transfer
						@change="nameChangeEvent({ row })"></vxe-input>
				</template>
			</vxe-column>

			<vxe-column field="businessLicenseEnd" title="营业执照公示结束时间" :edit-render="{ autofocus: '.vxe-input--inner' }"
				width="150" :visible="queryParams.contractType == 4">
				<template #edit="{ row }">
					<vxe-input v-model="row.businessLicenseEnd" type="date" placeholder="请选择日期" transfer
						@change="nameChangeEvent({ row })"></vxe-input>
				</template>
			</vxe-column>

			<vxe-column field="" title="公示倒计时" width="100" :visible="queryParams.contractType == 4">
				<template #default="{ row }">
					<span>{{ formatCountDown(row) }}</span>
				</template>
			</vxe-column>

			<vxe-column field="gmtCreate" title="开始时间" width="125">
				<template #default="{ row }">
					<span>{{ row.gmtCreate }}</span>
				</template>
			</vxe-column>

			<vxe-column title="操作" width="400" :visible="queryParams.status != 5">
				<template #default="{ row }">
					<el-button size="mini" type="text" icon="el-icon-video-pause" @click="suspendBtn(row, 1)"
						v-if="row.taskStatus === 2">开始
					</el-button>
					<el-button size="mini" type="text" icon="el-icon-video-pause" @click="suspendBtn(row, 2)"
						v-if="row.taskStatus === 1">暂停
					</el-button>
					<el-button size="mini" type="text" icon="el-icon-delete-solid" @click="suspendBtn(row, 3)"
						v-if="row.taskStatus == 1 || row.taskStatus == 2">作废
					</el-button>
					<el-button size="mini" type="text" icon="el-icon-check" @click="suspendBtn(row, 5)"
						v-if="row.taskStatus == 1">任务完成
					</el-button>
					<el-button size="mini" type="text" icon="el-icon-mouse" @click="insideTaskBtn(row, '内勤派单')"
						v-if="row.taskStatus == 1">内勤派单
					</el-button>
					<el-button size="mini" type="text" icon="el-icon-sunny" @click="insideTaskBtn(row, '外勤派单')"
						v-if="row.taskStatus == 1">外勤派单
					</el-button>
					<!-- <el-button size="mini" type="text" icon="el-icon-document" @click="taskListBtn(row)"
						v-if="row.taskStatus == 1">任务列表
					</el-button> -->
					<el-popover placement="bottom" width="720" trigger="hover" @show="taskListBtn(row)">
						<span slot="reference" class="iconfont ali-iconliebiao1"
							style="color: #1890ff;margin-left: 5px;">派单列表</span>
						<el-table :data="taskList">
							<el-table-column label="办理人" align="center" prop="handleName" />
							<el-table-column label="办理内容" align="center" prop="handleContent" />
							<el-table-column label="失败原因" align="center" prop="failReason" />
							<el-table-column label="任务发送时间" align="center" prop="gmtCreate">
								<template slot-scope="scope">
									<span>{{ parseTime(scope.row.gmtCreate, "{y}-{m}-{d}") }}</span>
								</template>
							</el-table-column>
							<el-table-column label="完结时间" align="center" prop="resultTime" width="180">
								<template slot-scope="scope">
									<span>{{ parseTime(scope.row.resultTime, "{y}-{m}-{d}") }}</span>
								</template>
							</el-table-column>
						</el-table>
					</el-popover>
				</template>
			</vxe-column>

		</vxe-table>

		<!-- 图片上传 -->
		<el-dialog ref="previewPdf" :visible.sync="uploadImgVis" :modal="true" width="35%"
			:title="queryParams.status != 5 ? '图片上传' : '图片查看'" append-to-body>
			<div v-if="imageSrc !== ''">
				<img :src="imageSrc" style="width: 100%;" height="30%" />
				<div style="line-height: 50px" v-if="queryParams.status != 5">
					提示：可通过下方上传控件进行重新上传该图片
				</div>
			</div>
			<!-- <div v-else>您没有之前上传的照片可预览</div> -->
			<el-upload class="upload-demo" drag v-if="queryParams.status != 5" :action="uploadImgUrl" :headers="headers"
				:on-success="imgSuccess" :before-upload="handleBeforeUpload"
				:data="{ contractId: this.contractId, customId: this.customId, contractType: this.queryParams.contractType, businessId: this.businessId }"
				accept=".jpeg,.jpg,.png" ref="uploadImg">
				<i class="el-icon-upload"></i>
				<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
				<div class="el-upload__tip" slot="tip">
					<span>只能上传jpg/png文件</span>
					<el-button v-show="imageSrc !== ''" size="mini" type="primary" style="float: right;"
						@click="downLoadImg()">下载图片</el-button>
					<el-button v-show="imageSrc !== ''" size="mini" type="primary" style="float: right;margin-right: 10px;"
						@click="removeImg()">删除图片</el-button>
				</div>
			</el-upload>
		</el-dialog>

		<!-- 内勤派单dia -->
		<el-dialog ref="insideTaskRef" :visible.sync="insideTaskVis" :modal="true" width="50%" height="50%"
			:title="taskVisTitle" append-to-body>
			<el-row :gutter="15">
				<el-form ref="elForm" :model="insideTaskForm" :rules="rules" size="medium" label-width="100px">
					<el-col :span="24" v-if="taskVisTitle === '外勤派单'">
						<el-form-item label="办理内容" prop="handleContent">
							<el-input type="textarea" :rows="2" placeholder="请输入办理内容" v-model="insideTaskForm.handleContent">
							</el-input>
						</el-form-item>
					</el-col>

					<el-col :span="24">
						<el-form-item label="选择人的名称" prop="handleName">
							<el-select v-model="insideTaskForm.handleName" placeholder="请选择选择人的名称" style="width: 100%">
								<el-option v-for="item in internalStaff" :key="item.userName" :value="item.userName"
									:disabled="item.disabled" :label="item.nickName">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-form>
			</el-row>

			<div slot="footer">
				<el-button @click="insideTaskFormClose"> 取消 </el-button>
				<el-button type="primary" @click="insideTaskFormConfirm">
					确定
				</el-button>
			</div>
		</el-dialog>

		<!-- 任务列表dia -->
		<el-dialog ref="taskListRef" :visible.sync="taskListVis" :modal="true" width="50%" height="50%" title="任务列表"
			append-to-body>
			<el-row :gutter="15">
				<el-table :data="taskList">
					<el-table-column label="办理人" align="center" prop="handleName" />

					<el-table-column label="办理内容" align="center" prop="handleContent" />
					<el-table-column label="失败原因" align="center" prop="failReason" />
					<el-table-column label="任务发送时间" align="center" prop="gmtCreate">
						<template slot-scope="scope">
							<span>{{ parseTime(scope.row.gmtCreate, "{y}-{m}-{d}") }}</span>
						</template>
					</el-table-column>
					<el-table-column label="完结时间" align="center" prop="resultTime" width="180">
						<template slot-scope="scope">
							<span>{{ parseTime(scope.row.resultTime, "{y}-{m}-{d}") }}</span>
						</template>
					</el-table-column>
				</el-table>
			</el-row>

			<div slot="footer">
				<el-button @click="taskListClose"> 取消 </el-button>
				<el-button type="primary" @click="taskListClose"> 确定 </el-button>
			</div>
		</el-dialog>

		<el-dialog :visible.sync="pdfDialog.show" title="查看门户" width="40%">
			<div class="dialog-wrap">
				<div class="item-title">{{ pdfDialog.title }}</div>
				<div class="item-content-wrap">
					<el-scrollbar>
						<div class="item-content">
							<div class="pdf" id="pdfView"></div>
						</div>
					</el-scrollbar>
				</div>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import {
	updateContractCustom,
	previewImage,
	listOfContractType,
	loadContractImage,
	deleteContractImage
} from "@/api/system/info";
import Compressor from 'compressorjs';
import { updateRemark, listRemark } from "@/api/system/remark";
import { pcaTextArr } from "element-china-area-data";
import second from "@/components/Crontab/second.vue";
import { getToken } from "@/utils/auth";
import { listUser } from "@/api/system/user";
import request from '@/utils/request'
import { addTask } from "@/api/outsideTask/outSidetask";
import {
	addInsideTask,
	getTaskList,
	operate,
} from "@/api/outsideTask/inSidetask";
import { allocatedUserList } from "@/api/system/role";
import Pdfh5 from "pdfh5";
import "pdfh5/css/pdfh5.css";
import searchOption from "@/components/searchOption";
import { min } from 'moment';

export default {
	name: "Info",
	components: {
		searchOption
	},
	dicts: ["contract_type"],
	data() {
		return {
			downLoadImgObj: {},
			popViewImgFlag: true,
			requeryFlag: true,
			autoTableHeight: 750,
			pcaTextArr,
			internalStaff: [],
			openRecord: false,
			openContract: false,
			remarkList: [],
			checkList1: [],
			checkList2: [],
			checkList3: [],
			checkList4: [],
			checkList: [],
			loading: true,

			// 选中数组
			ids: [],
			// 非单个禁用
			single: true,
			// 非多个禁用
			multiple: true,
			// 显示搜索条件
			showSearch: true,
			// 总条数
			total: 0,
			// 客户信息表格数据
			infoList: [],
			// 弹出层标题
			title: "",
			// 是否显示弹出层
			open: false,
			callPhone: "",
			// 查询参数
			queryParams: {
				pageNum: 1,
				pageSize: 30,
				contractType: 2,
				customName: null,
				legalName: null,
				customNumber: null,
				legalPersonNumber: null,
				source: null,
				province: null,
				city: null,
				region: null,
				adressDetail: null,
				accountNo: null,
				bussLicenseImage: null,
				bussLicenseImageMinor: null,
				legalIdCardFront: null,
				legalIdCardBack: null,
				callPhone: null,
				callName: null,
				customManager: null,
				gmtCreate: null,
				successTime: null,
				status: 0,
				degree: null,
			},
			// 表单参数
			form: {
				contractType: 0,
			},
			queryEmp: {
				pageNum: 1,
				pageSize: 30,
				deptId: 200,
			},
			dateRange: [],
			breadList: [], //初始化
			// 表单校验
			rules: {},
			rowId: "",

			uploadImgUrl:
				process.env.VUE_APP_BASE_API + "/custom/info/uploadContractImage",
			headers: {
				Authorization: "Bearer " + getToken(),
			},

			uploadImgVis: false,
			imageSrc: "",
			customId: "",
			uploadKey: "",
			businessId: null,
			contractId: null,
			popoverVis: false,
			hoverId: "",
			insideTaskVis: false,
			//内勤派单form
			insideTaskForm: {
				customId: null,
				contractId: null,
				handleContent: null,
				handleName: null,
			},
			taskListVis: false,
			taskList: [],
			taskVisTitle: "",

			pdfDialog: {
				show: false,
				title: "",
			},
			pdfh5: null,
			// 所有需要上传图片的项目名
			uploadImgItem: [],

		};
	},
	created() {
		// this.getList();
		// this.listUser();
	},
	watch: {
		// 监听路由对象中的变化
		'$route': {
			handler: function (from, to) {
				// 当路由发生变化时会调用这个函数
				this.infoList = [];
				this.queryParams.pageNum = 1;
				this.queryParams.pageSize = 30;
				this.queryParams.contractType = from.query.contractType;
				this.queryParams.status = from.query.status;
				this.getList();
				//动态设置部分列头
				let columnId = null;
				let uploadCol = this.$store.state.user.contractTypeUpload;
				uploadCol.forEach(element => {
					if (element.dictValue == from.query.contractType) {
						columnId = element.remark.split(",");
					}
				});
				let contractUploadItems = this.$store.state.user.contractUploadItems;
				contractUploadItems.forEach(element => {
					if (columnId.includes(element.dictValue)) {
						this.uploadImgItem.push(element);
					}
				});
			},
			// 如果需要在路由变化时立即响应，可以设置immediate为true
			immediate: true
		}
	},
	computed: {
		second() {
			return second;
		},
		// 个税密码，税务密码显示条件  仅变更，资质列表隐藏
		taxVisible() {
			if (this.queryParams.contractType == 3 || this.queryParams.contractType == 5 || this.queryParams.contractType == 200) {
				return false
			} else {
				return true
			}
		},
		// 显示上传图片或查看图片
		contractItem(row, id) {
			return function (row, id) {
				let allItem = row.contractItem;
				if (allItem == null || allItem == '') {
					return false
				} else {
					let itemArray = allItem.split(";");
					let ids = []
					for (let i = 0; i < itemArray.length; i++) {
						ids.push(itemArray[i].split(',')[0])
					}
					if (ids.includes(id)) {
						return true
					} else {
						return false
					}
				}
			}
		},
		//
		// 上传图片项是否显示“客户未涉及”
		imgPath(row, id) {
			return function (row, id) {
				let allItem = row.contractItem;
				if (allItem == null || allItem == '') {
					return false
				} else {
					let itemArray = allItem.split(";");
					for (let i = 0; i < itemArray.length; i++) {
						let key = itemArray[i].split(',')[0];
						let value = itemArray[i].split(',')[1];
						if (id == key) {
							if (value == '-1') {
								return true
							} else {
								return false
							}
						}
					}
				}
			}
		}
	},
	mounted() {
		this.$nextTick(() => {
			// 视口高度 - 列表上方的元素高度
			let allHeight = window.innerHeight;
			let element = [
				document.getElementById('navbar'),
				document.getElementById('searchForm'),
				document.getElementById('tags-view-container'),
			]
			let domHeight = element.map(item => item.offsetHeight)
			// let tableHeight = allHeight - 50 - 34 - 50 - 36;
			let tableHeight = allHeight - 40 - domHeight[0] - domHeight[1] - domHeight[2];
			this.autoTableHeight = tableHeight;
		})
	},
	methods: {
		// 搜索子组件触发搜索
		parentSearchList(data) {
			this.queryParams.pageNum = data.pageNum;
			this.queryParams.pageSize = data.pageSize;
			this.queryParams.callName = data.callName;
			this.queryParams.callPhone = data.callPhone;
			this.queryParams.customName = data.customName;
			this.queryParams.customManager = data.customManager;
			this.handleQuery();
		},
		listUser(num, row) {
			allocatedUserList({
				pageNum: 1,
				pageSize: 999,
				roleId: num,
				userName: undefined,
				phonenumber: undefined,
			}).then((response) => {
				this.internalStaff = response.rows;
				this.taskListBtn(row, true)
			});
		},
		//托管任务 注册任务 倒计时提醒   其他任务正向提醒
		formatDate(date, taskStatus) {
			if (taskStatus == 1) {
				if (date == null) {
					return '未知'
				}
				let gmtCreate = date.split(' ')[0];//合同创建时间
				gmtCreate = gmtCreate.split('-')[0] + gmtCreate.split('-')[1] + gmtCreate.split('-')[2]
				let nowDate = new Date();
				const year = nowDate.getFullYear();
				const month = String(nowDate.getMonth() + 1).padStart(2, '0');
				const day = String(nowDate.getDate()).padStart(2, '0');
				let formatDates = year + month + day;
				//托管任务 注册任务
				let minus = parseInt(formatDates) - parseInt(gmtCreate);
				if (this.queryParams.contractType == 2 || this.queryParams.contractType == 1) {
					// 倒计时计算 当前时间 - gmtCreate -7    倒计时最大为7，最小为0，小于0时设为0
					let Countdown = null
					if (this.queryParams.contractType == 2) {// 托管 倒计时为7  注册 倒计时为3
						Countdown = 7
					} else {
						Countdown = 3
					}
					if (minus > Countdown) {
						minus = Countdown;
					}
					let days = Math.abs(minus - Countdown);
					return days;
				} else {
					// 正向提醒天数
					if (minus == 0) {
						minus = 1;
					}
					return minus
				}
			} else if (taskStatus == 2) {
				return '已暂停'
			} else if (taskStatus == 3) {
				return '已作废'
			} else if (taskStatus == 4) {
				return '已完成'
			}
		},
		//公示时间倒计时
		formatCountDown(row) {
			console.log(row);
			let startTime = row.businessLicenseStart;
			let endTime = row.businessLicenseEnd;
			if (startTime == null || endTime == null) {
				return null
			}
			startTime = new Date(startTime);
			endTime = new Date(endTime);
			const diff = Math.abs(endTime - startTime);
			const days = Math.ceil(diff / (1000 * 60 * 60 * 24));
			return days;
		},
		/** 查询客户信息列表 */
		getList() {
			this.loading = true;
			this.queryParams.pageNum = 1;
			listOfContractType(this.queryParams).then((response) => {
				this.infoList = response.rows;
				this.total = response.total;
				this.loading = false;
			});
		},
		nameChangeEvent({ row }) {
			let form = row;
			updateContractCustom(form).then((response) => {
				// this.getList();
			});
		},

		// 取消按钮
		cancel() {
			this.open = false;
		},
		// 取消按钮
		cancelContract() {
			this.openContract = false;
			this.reset();
		},
		// 表单重置
		reset() {
			this.form = {
				id: null,
				customName: null,
				legalName: null,
				customNumber: null,
				legalPersonNumber: null,
				source: null,
				province: null,
				city: null,
				region: null,
				schedule: null,
				adressDetail: null,
				accountNo: null,
				bussLicenseImage: null,
				bussLicenseImageMinor: null,
				legalIdCardFront: null,
				legalIdCardBack: null,
				callPhone: null,
				callName: null,
				customManager: null,
				gmtCreate: null,
				successTime: null,
				status: null,
			};
			this.resetForm("form");
		},
		talkBackHistory(row) {
			this.openRecord = true;
			let customId = row.id;
			let queryParams = {
				pageNum: 1,
				pageSize: 30,
			};
			if (customId) {
				queryParams.customId = customId;
			}
			listRemark(queryParams).then((response) => {
				this.remarkList = response.rows;
			});
		},
		createContract(row) {
			this.openContract = true;
			this.rowId = row.id;
		},

		srcollFn(e) {
			let circulateNum = this.total / 30;
			let bottomOffset = e.scrollHeight - e.scrollTop - e.bodyHeight;
			if (bottomOffset < 50 && this.queryParams.pageNum < circulateNum) {
				if (this.requeryFlag) {
					this.loading = true;
					this.queryParams.pageNum++;
					this.requeryFlag = false;
					listOfContractType(this.queryParams).then((response) => {
						this.infoList = [...this.infoList, ...response.rows];
						// this.total = response.total;
						this.loading = false;
						this.requeryFlag = true;
					});
				}
			}
		},
		// 图片上传项，不需要上传    或    删除图片
		noNeedToUpload(row, key) {
			this.$modal.confirm('确认客户不涉及此上传项吗？').then(() => {
				this.businessId = key;
				this.downLoadImgObj = row;
				request({
					url: "/custom/info/uploadContractImageNULL",
					headers: {
						'Authorization': "Bearer " + getToken()
					},
					method: 'post',
					data: {
						businessId: key,
						customId: row.row.customId,
						contractId: row.row.contractId,
						contractType: this.queryParams.contractType,
					}
				}).then(response => {
					this.uploadKey = '-1';
					this.successActions(true)
				})
			})
		},
		// 图片上传之前压缩图片质量
		handleBeforeUpload(file) {
			return true
			// console.log('文件', file);
			// if (file.size > 10485760) {
			// 	this.$modal.msgError('图片大小超出最大限制，请重新拍摄')
			// 	return false;
			// }
			// return new Promise((resolve, reject) => {
			// 	new Compressor(file, {
			// 		quality: 0.5, // 设置压缩质量
			// 		success(result) {
			// 			console.log(result);
			// 			resolve(result);
			// 		},
			// 		error(err) {
			// 			reject(err);
			// 		},
			// 	});
			// })
		},
		//上传图片
		uploadTableImg(row, key, boolean) {
			if (!boolean) {
				this.imageSrc = '';
			}
			this.downLoadImgObj = row;
			this.downLoadImgObj.key = key;
			// if (this.queryParams.status == 5) {
			// 	return
			// }
			this.uploadImgVis = true;
			// this.uploadKey = key;
			this.customId = row.row.customId;
			this.contractId = row.row.contractId;
			this.businessId = key;
			this.$refs.uploadImg.clearFiles();
			// this.successAction();
		},
		// 图片上传成功后的回调
		imgSuccess(response) {
			this.$modal.msgSuccess("上传成功");
			this.uploadKey = response.data;
			this.successActions(true);
		},
		//请求图片  预览
		successActions(flag, type, row, key) {
			// flag为true代表需要更新本条数据的contractItem字段
			if (flag) {
				if (this.downLoadImgObj.row !== undefined) {
					let imgUrlStr = this.downLoadImgObj.row.contractItem
					// 先检查是否已有相同businessId和文件名，有则删除
					if (imgUrlStr != '' && imgUrlStr != null) {
						let itemArray = imgUrlStr.split(';');
						for (let i = 0; i < itemArray.length; i++) {
							let item = itemArray[i];
							let itemArr = item.split(',');
							if (itemArr[0] == this.businessId) {
								itemArray.splice(i, 1);
								break;
							}
						}
						imgUrlStr = itemArray.join(';');
					}
					if (imgUrlStr == '' || imgUrlStr == null) {
						imgUrlStr = `${this.businessId},${this.uploadKey}`
					} else {
						imgUrlStr += `;${this.businessId},${this.uploadKey}`
					}
					this.downLoadImgObj.row.contractItem = imgUrlStr;
				}
				// this.getList();
			}
			this.imageSrc = "";
			if (this.uploadKey == '-1') {
				return
			}
			loadContractImage(this.uploadKey).then((response) => {
				if (response.type === "image/jpg") {
					const blobData = {};
					blobData.type = "application/image;chartset=UTF-8";
					this.imageSrc = window.URL.createObjectURL(
						new Blob([response], blobData)
					);
					this.popViewImgFlag = true;
					if (type == 'upload') {
						setTimeout(() => {
							this.uploadTableImg(row, key, true)
						}, 500)
					}
				}
			}).catch(() => {
				this.imageSrc = "";
				this.popViewImgFlag = true;
				// this.$modal.msgError('图片加载失败');
				// if (type) {
				// 	this.uploadTableImg(row, key, true)
				// }
			});
		},

		//查看图片  查找文件名
		popoverFc(row, key) {
			if (!this.popViewImgFlag) {
				return
			}
			this.popViewImgFlag = false;
			this.downLoadImgObj = row;
			this.downLoadImgObj.key = key;
			let contractItem = row.row.contractItem;
			if (contractItem == '' || contractItem == null) {
				return
			} else {
				let itemArray = contractItem.split(';');
				for (let i = 0; i < itemArray.length; i++) {
					if (itemArray[i].split(',')[0] == key) {
						this.uploadKey = itemArray[i].split(',')[1];
						break;
					}
				}
				this.successActions(false, 'upload', row, key);
			}
		},
		// 行背景颜色
		rowStyle({ row }) {
			// 已暂停
			if (row.taskStatus == 2) {
				return {
					backgroundColor: "#FF9192",
				};
			} else if (row.taskStatus == 3) {
				return {
					backgroundColor: "#d1cece",
				};
			}
		},
		//操作列 --暂停
		suspendBtn(row, status) {
			let id = row.taskId;
			let text = '';
			switch (status) {
				case 1:
					text = '是否开始任务？'
					break;
				case 2:
					text = '是否暂停任务？'
					break;
				case 3:
					text = '确认作废吗？'
					break;
				case 5:
					text = '是否完成任务？'
					break;
				default:
					break;
			}
			this.$modal
				.confirm(text)
				.then(function () { })
				.then(() => {
					let params = {
						id: row.contractId,
						taskId: id,
						status: status,
						contract_notes: ''
					}
					operate(params).then((response) => {
						if (response.code === 200) {
							this.getList();
						}
					});
				})
				.catch(() => { });
		},
		//内勤、外勤派单触发
		insideTaskBtn(row, type) {
			this.taskVisTitle = type;
			this.insideTaskForm.customId = row.customId;
			this.insideTaskForm.taskId = row.taskId;
			this.insideTaskForm.contractId = row.contractId;
			this.queryEmp.deptId = 105;
			this.internalStaff = [];
			if (type == '内勤派单') {
				this.listUser(114, row);
			} else {
				this.listUser(108, row);
			}
			this.insideTaskVis = true;
			// 调用派单列表接口，查询之前的已派单人，每个任务不可重复给同一个员工派单
			// this.taskList = [];
			// this.insideTaskVis = false;
		},
		// 确认 派单
		insideTaskFormConfirm() {
			if (this.taskVisTitle === "内勤派单") {
				let params = {
					taskId: this.insideTaskForm.taskId,
					customId: this.insideTaskForm.customId,
					contractId: this.insideTaskForm.contractId,
					handleContent: this.insideTaskForm.handleContent,
					handleName: this.insideTaskForm.handleName,
				};
				console.log(params);
				addInsideTask(params).then((response) => {
					if (response.code === 200) {
						this.insideTaskFormClose();
						this.$modal.msgSuccess("派单成功");
					}
				});
			} else {
				let params = {
					taskId: this.insideTaskForm.taskId,
					customId: this.insideTaskForm.customId,
					contractId: this.insideTaskForm.contractId,
					handleContent: this.insideTaskForm.handleContent,
					handleName: this.insideTaskForm.handleName,
					status: 3,
				};
				console.log(params);
				addTask(params).then((response) => {
					if (response.code === 200) {
						this.insideTaskFormClose();
						this.$modal.msgSuccess("派单成功");
					}
				});
			}
		},
		// 表单关闭
		insideTaskFormClose() {
			this.insideTaskForm = {
				taskId: null,
				customId: null,
				contractId: null,
				handleContent: null,
				handleName: null,
			};
			this.insideTaskVis = false;
		},
		// 任务列表
		taskListBtn(row, type) {
			// this.taskListVis = true;
			getTaskList(row.contractId).then((response) => {
				if (response.code === 200) {
					this.taskList = response.rows;
				}
				// 派单时，已派单员工不可重复派单
				if (type) {
					let userArr = this.internalStaff;
					if (userArr.length > 0) {
						console.log('检查重复');
						for (let i = 0; i < userArr.length; i++) {
							for (let j = 0; j < this.taskList.length; j++) {
								if (userArr[i].userName == this.taskList[j].handleName) {
									userArr[i].disabled = true;
								}
							}
						}
					}
				}
			});
		},
		// 任务列表关闭
		taskListClose() {
			this.taskListVis = false;
		},
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.pageNum = 1;
			this.getList();
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.resetForm("queryForm");
			this.handleQuery();
		},
		// 业务描述 查看图片
		popoverImg(row) {
			let url = '';
			url = `/task/${row.contractId}.png`;
			this.imageSrc = "";
			previewImage(url).then((response) => {
				if (response.type === "image/jpg") {
					const blobData = {};
					blobData.type = "application/image;chartset=UTF-8";
					this.imageSrc = window.URL.createObjectURL(
						new Blob([response], blobData)
					);
				}
			});
		},
		// 图片下载
		downLoadImg() {
			let fileName = '';
			let key = this.downLoadImgObj.key;
			let allItem = this.downLoadImgObj.row.contractItem;
			let itemArray = allItem.split(";");
			for (let i = 0; i < itemArray.length; i++) {
				if (itemArray[i].split(',')[0] == key) {
					fileName = itemArray[i].split(',')[1];
					break
				}
			}
			this.$download.downloadFile('/common/downloadFile', fileName, false, false, fileName);
		},
		// 图片删除
		removeImg() {
			let that = this;
			this.$modal.confirm('是否确认删除该图片？').then(function () {

			}).then(() => {
				let rarams = {
					businessId: this.businessId,
					customId: this.downLoadImgObj.row.customId,
					contractId: this.downLoadImgObj.row.contractId,
					contractType: this.queryParams.contractType,
				}
				deleteContractImage(rarams).then(() => {
					this.imageSrc = "";
					this.uploadImgVis = false;
					// 本地删除文件名
					let allItem = this.downLoadImgObj.row.contractItem.split(";");
					for (let i = 0; i < allItem.length; i++) {
						const element = allItem[i];
						if (element.split(',')[0] == this.downLoadImgObj.key) {
							allItem.splice(i, 1);
							break
						}
					}
					this.downLoadImgObj.row.contractItem = allItem.join(';');
					this.$modal.msgSuccess("删除成功");
				})
				// this.noNeedToUpload(that.downLoadImgObj.row, that.downLoadImgObj.key, 'noHint')
			})
		}
	},
};
</script>

<style scoped>
.el-row {
	margin-bottom: 20px;
}

.newTree /deep/ .el-tree-node__content {
	height: 40px !important;
}

.vxe-table--render-default /deep/ .vxe-body--row /deep/ .row--current {
	background-color: #90f1fc;
}

.newdialog .el-row {
	margin-bottom: 0px !important;
}

.width18 {
	width: 180px;
}

.item-content /deep/ .pdfjs {
	height: 800px !important;
}

.upload-demo /deep/ .el-upload {
	width: 100% !important;
}
</style>